package com.cxx.controller;

import com.aliyuncs.exceptions.ClientException;
import com.cxx.log.Log;
import com.cxx.mapper.UserMapper;
import com.cxx.pojo.Result;
import com.cxx.pojo.User;
import com.cxx.service.UserService;
import com.cxx.utils.AliOssUtil;
import com.cxx.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/person-web/api/*")
public class UserController {
    @Autowired
    private AliOssUtil aliOssUtil;
    @Autowired
    private UserService userService;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private JwtUtils jwtUtils;
    @GetMapping("/userInfo")
    @Log
    public Result adminInfo(String token){
        Claims claims=jwtUtils.parseJwt(token);
        String account=(String) claims.get("name");
        User user=userMapper.selectByUserAccount(account);
        return Result.sucess(user);
    }
    @PostMapping("/userUpdate")
    @Log
    public void userUpdate(MultipartFile image,User user,String token) throws IOException, ClientException {
        Claims claims=jwtUtils.parseJwt(token);
        String account=(String) claims.get("name");
        user.setUserName(account) ;
        if(image!=null){
            //修改图片，删除之前的图片，并修改信息
            User userBefore= userMapper.selectByUserAccount(account);
            String imgBefore=userBefore.getUserImgUrl();
            if(imgBefore!=null){
                aliOssUtil.deleteImg(imgBefore);
            }
            String imgurl=aliOssUtil.upload(image);
            user.setUserImgUrl(imgurl);
            userService.updateUser(user);
        }else {
            //不修改图片，直接修改信息
            userService.updateUser(user);
        }

    }
}
